import React, { useState, useEffect} from 'react';
import { useRequest } from 'ahooks';
import { Space, DatePicker, message, Empty } from 'antd';
import { RangePickerProps } from 'antd/es/date-picker/generatePicker';
import { connect, Dispatch } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import { ProCard } from '@ant-design/pro-card';
import { FETCH_OVERVIEW, FETCH_LASTWILLPRD_STATISTICS, FETCH_ALREADYPRD_STATISTICS,
  FETCH_NOTPRD_STATISTICS, FETCH_RANKINGS } from '@/actions/dashboard';
import { ConnectState } from '@/models/connect';
import { DateTypeEnum, ProjectOverviewDataType, ProjectStatisticsDataType, ProjectStatisticDataType,
  ProjectRankingDataType, ProjectOverviewRadarDataType } from '@/types/dashboard';
import { getSystemCode } from '@/utils/authority';
import { getDateTime, dateFormat, timeFormat } from '@/utils/utils';
import { ProjectOverviewCard, ProjectOverviewRadarCard, ProjectStatisticLineCard, ProjectRankingCard} from './components';
import { getTimeDistance } from './utils/utils';
import styles from './style.less';

const { RangePicker } = DatePicker;

interface AnalysisProps {
  dispatch: Dispatch;
  overviewDatas: ProjectOverviewDataType;
  lastWillPrdDatas: ProjectOverviewRadarDataType;
  statisticsDatas: ProjectStatisticsDataType[];
  alreadyPrdStatisticDatas: ProjectStatisticDataType[];
  notPrdStatisticDatas: ProjectStatisticDataType[];
  rankingDatas: ProjectRankingDataType[];
  overviewLoading: boolean;
  lastWillPrdLoading: boolean;
  statisticsLoading: boolean;
  alreadyPrdStatisticLoading: boolean;
  notPrdStatisticLoading: boolean;
  rankingsLoading: boolean;
}

type RangePickerValue = RangePickerProps<moment.Moment>['value'];

const month = getTimeDistance('month');
const dateFormatPattern2 = 'YYYYMMDD';

const Analysis: React.FC<AnalysisProps> = (props) => {
  // const [currentTabKey, setCurrentTabKey] = useState<string>('GBSP');
  const [rangePickerValue, setRangePickerValue] = useState<RangePickerValue>(month);

  useEffect(() => {
    console.info('Analysis.useEffect');
    const systemCode = getSystemCode();
    let reqRef = 0;
    const { dispatch } = props;
    reqRef = requestAnimationFrame(() => {
      dispatch(FETCH_OVERVIEW({
        systemCode
      }));
      dispatch(FETCH_LASTWILLPRD_STATISTICS({
        systemCode
      }));
      // dispatch(FETCH_STATISTICS({
      //   systemCode
      // }));
      dispatch(FETCH_ALREADYPRD_STATISTICS({
        systemCode
      }));
      dispatch(FETCH_NOTPRD_STATISTICS({
        systemCode
      }));
      // console.info(rangePickerValue);
      if (rangePickerValue) {
        const startDate = rangePickerValue?.[0]?.format(dateFormatPattern2);
        const endDate = rangePickerValue?.[1]?.format(dateFormatPattern2);
        dispatch(FETCH_RANKINGS({
          systemCode,
          startDate,
          endDate
        }));
      }
    });
    // 开启一个定时任务
    fetchLastWillPrdStatistic.run();
    return () => {
      cancelAnimationFrame(reqRef);
      fetchLastWillPrdStatistic.cancel();
    }
  }, []);

  /**
   * 定义一个轮询任务
   */
  const fetchLastWillPrdStatistic = useRequest(() => {
    const systemCode = getSystemCode();
    const { dispatch } = props;
    console.info('发起最近一次投产集群数据分布查询');
    return dispatch(FETCH_LASTWILLPRD_STATISTICS({
      systemCode
    }));
  }, {
    manual: true,
    pollingInterval: 1000*60*3,
    pollingWhenHidden: false
  });

  const handleRangePickerChange = (rangePickerValue: RangePickerValue) => {
    setRangePickerValue(rangePickerValue);
    const systemCode = getSystemCode();
    const { dispatch } = props;
    if (rangePickerValue) {
      const startDate = rangePickerValue?.[0]?.format(dateFormatPattern2);
      const endDate = rangePickerValue?.[1]?.format(dateFormatPattern2);
      dispatch(FETCH_RANKINGS({
        systemCode,
        startDate,
        endDate
      }));
    }
  };

  const selectDate = (type: DateTypeEnum) => {
    const value = getTimeDistance(type);
    handleRangePickerChange(value);
  };

  const isActive = (type: DateTypeEnum) => {
    if (!rangePickerValue) {
      return '';
    }
    const value = getTimeDistance(type);
    if (!value) {
      return '';
    }
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return '';
    }
    if (
      rangePickerValue[0].isSame(value[0] as moment.Moment, 'day') &&
      rangePickerValue[1].isSame(value[1] as moment.Moment, 'day')
    ) {
      return styles.currentDate;
    }
    return '';
  };

  const overviewCardOnClick = (dataKind: string, type: string, systemCode: string) => {
    // console.info('cardOnClick', dataKind, type, systemCode);
    // 弹窗表格展示
    message.success('请暂时通过需求列表，任务列表两个交易查询详细信息');
  }

  const {
    // 项目概要
    overviewDatas, overviewLoading,
    // 项目最近投产
    lastWillPrdDatas, lastWillPrdLoading,
    // 项目已经投产
    alreadyPrdStatisticDatas, alreadyPrdStatisticLoading,
    // 项目未投产
    notPrdStatisticDatas, notPrdStatisticLoading,
    // 排行榜
    rankingDatas, rankingsLoading 
  } = props;
  // console.info('rankingDatas', rankingDatas);
  const { lastWillPrdDate } = lastWillPrdDatas;
  const { recordDate, recordTime } = overviewDatas;
  const timeStr = `${dateFormat(recordDate)} ${timeFormat(recordTime)}`
  const overviewCardTitle = `项目任务概览，数据统计时间 ${timeStr}`
  const lastWillPrdCardTitle = `最近一次投产(${lastWillPrdDate})集群数据分布`;
  const dateTimeStr = getDateTime();

  return (
    <PageContainer
      extra={dateTimeStr}
    >
      <Space direction='vertical' size='middle' style={{ 'display': 'flex' }}>
        <ProCard split={'vertical'}>
          <ProCard title={overviewCardTitle} colSpan='60%'>
            <ProjectOverviewCard
              loading={overviewLoading}
              overviewDatas={overviewDatas}
              cardOnClick={overviewCardOnClick}
            />
          </ProCard>
          <ProCard title={lastWillPrdCardTitle} loading={lastWillPrdLoading}>
            <ProjectOverviewRadarCard
              loading={lastWillPrdLoading}
              radarDatas={lastWillPrdDatas}
            />
          </ProCard>
        </ProCard>
        <ProCard split={'vertical'}>
          <ProCard title='已投产需求数据统计（按月份统计）' colSpan='50%' loading={alreadyPrdStatisticLoading}>
            <ProjectStatisticLineCard
              statisticDatas={alreadyPrdStatisticDatas}
            />
          </ProCard>
          <ProCard title='未投产需求数据统计（按月份统计）' colSpan='50%' loading={notPrdStatisticLoading}>
            <ProjectStatisticLineCard
              statisticDatas={notPrdStatisticDatas}
            />
          </ProCard>
        </ProCard>
        <ProCard split={'vertical'}>
          <ProCard title='项目数据排名'
            extra={
              <div className={styles.salesExtraWrap}>
                <div className={styles.salesExtra}>
                  <a className={isActive('week')} onClick={() => selectDate('week')}>
                    本周
                  </a>
                  <a className={isActive('month')} onClick={() => selectDate('month')}>
                    本月
                  </a>
                  <a className={isActive('year')} onClick={() => selectDate('year')}>
                    本年
                  </a>
                </div>
                <RangePicker
                  value={rangePickerValue}
                  onChange={handleRangePickerChange}
                  style={{ width: 256 }}
                />
              </div>
            }
            loading={rankingsLoading}
          >
            { rankingDatas.length> 0 ? 
              rankingDatas.map((value) => {
                const { kind, rankingData } = value;
                return (
                  <ProCard key={kind} bordered>
                    <ProjectRankingCard kind={kind} rankingDatas={rankingData} />
                  </ProCard>
                );
              }) : <Empty />
            }
          </ProCard>
        </ProCard>
      </Space>
    </PageContainer>
  );
}

export default connect(({ dashboards, loading }: ConnectState) => ({
  overviewDatas: dashboards.overviewDatas,
  lastWillPrdDatas: dashboards.lastWillPrdDatas,
  statisticsDatas: dashboards.statisticsDatas,
  alreadyPrdStatisticDatas: dashboards.alreadyPrdStatisticDatas,
  notPrdStatisticDatas: dashboards.notPrdStatisticDatas,
  rankingDatas: dashboards.rankingDatas,
  overviewLoading: loading.effects['dashboards/fetchOverview'],
  lastWillPrdLoading: loading.effects['dashboards/fetchStatisticOfLastWillPrd'],
  statisticsLoading: loading.effects['dashboards/fetchStatistics'],
  alreadyPrdStatisticLoading: loading.effects['dashboards/fetchStatisticOfAlreadyPrd'],
  notPrdStatisticLoading: loading.effects['dashboards/fetchStatisticOfNotPrd'],
  rankingsLoading: loading.effects['dashboards/fetchRankings'],
}))(Analysis);